using System;
using System.Collections.Generic;
using System.Text.Json;
using JlPay.Sdk.Core;
using JlPay.Sdk.Services;

namespace JlPay.Sdk.Models.BaseData
{
    /// <summary>
    /// 银行卡bin信息查询响应
    /// </summary>
    public class BankCardBinMatchingResponse : StandardResponse, IComplexFieldHandler
    {
        /// <summary>
        /// 数据
        /// </summary>
        public Dictionary<string, object>? Data { get; set; }

        /// <summary>
        /// 处理复杂字段，专门处理Data字段的解析
        /// </summary>
        /// <param name="fieldName">字段名</param>
        /// <param name="fieldValue">字段值</param>
        public void HandleComplexField(string fieldName, object fieldValue)
        {
            if (fieldName.ToLower() == "data" && fieldValue != null)
            {
                try
                {
                    if (fieldValue is Dictionary<string, object> dictValue)
                    {
                        Data = dictValue;
                    }
                    else if (fieldValue is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object)
                    {
                        var dict = new Dictionary<string, object>();
                        foreach (var jsonProp in jsonElement.EnumerateObject())
                        {
                            // 使用GetString()方法获取字符串值，避免保留JSON格式的引号
                            if (jsonProp.Value.ValueKind == JsonValueKind.String)
                            {
                                dict[jsonProp.Name] = jsonProp.Value.GetString();
                            }
                            else
                            {
                                // 对于非字符串类型，使用GetRawText()保持原始格式
                                dict[jsonProp.Name] = jsonProp.Value.GetRawText();
                            }
                        }
                        Data = dict;
                    }
                    else if (fieldValue is string stringValue)
                    {
                        try
                        {
                            var parsed = JsonSerializer.Deserialize<Dictionary<string, object>>(stringValue);
                            Data = parsed;
                        }
                        catch
                        {
                            // 解析失败，设置为空字典
                            Data = new Dictionary<string, object>();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"解析Data字段时出错: {ex.Message}");
                    Data = new Dictionary<string, object>();
                }
            }
        }

        /// <summary>
        /// 重写HandleResponse方法，确保响应报文格式完全符合预期
        /// </summary>
        /// <param name="operationName">操作名称</param>
        /// <param name="config">配置对象</param>
        public new void HandleResponse(string operationName, Config? config = null)
        {
            if (IsSuccess())
            {
                Console.WriteLine($"{operationName}成功！");
                
                // 添加调试信息，显示实际接收到的数据
                Console.WriteLine("=== 调试信息 ===");
                Console.WriteLine($"RetCode: {RetCode}");
                Console.WriteLine($"RetMsg: {RetMsg}");
                Console.WriteLine($"Data: {Data?.Count ?? 0} 个字段");
                if (Data != null && Data.Count > 0)
                {
                    Console.WriteLine("Data内容:");
                    foreach (var kvp in Data)
                    {
                        Console.WriteLine($"  {kvp.Key}: {kvp.Value}");
                    }
                }
                Console.WriteLine("=== 调试信息结束 ===");
                
                // 手动构建响应JSON，确保字段名称和结构完全符合预期
                var responseData = new Dictionary<string, object>
                {
                    ["ret_code"] = RetCode ?? "",
                    ["ret_msg"] = RetMsg ?? "",
                    ["data"] = Data ?? new Dictionary<string, object>()
                };
                
                Console.WriteLine("响应报文：" + JsonSerializer.Serialize(responseData, new JsonSerializerOptions 
                { 
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                }));
            }
            else
            {
                Console.WriteLine($"{operationName}失败: {RetCode} - {RetMsg}");
            }
        }
    }
} 